<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;

// 入库管理
class Storage extends Backend
{
    protected $model = null;

    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Depot.Storage.Storage');

        $this->SupplierModel = model('Depot.Supplier');

        $this->ProductModel = model('Product.Product');

        $this->DepotProductModel = model('Depot.Storage.Product');

        $this->BackModel = model('Depot.Back.Back');

        $this->view->assign("statuslist", $this->model->statuslist());
        $this->assignconfig("statuslist", $this->model->statuslist());
    }

    // 入库列表
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) 
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 商品入库
    public function add()
    {
        if($this->request->isPost())
        {
            $params = $this->request->post();
            
            if($params)
            {
                $ModelProduct = model('Product.Product');

                //入库插入
                $ModelStorage = model('Depot.Storage.Storage');
                $ModelStorageProduct = model('Depot.Storage.Product');
                $ModelStorage->startTrans();
                $ModelStorageProduct->startTrans();

                //循环入库商品
                $prolist = isset($params['prolist']) ? $params['prolist'] : [];
                $nums = isset($params['nums']) ? $params['nums'] : [];
                $price = isset($params['price']) ? $params['price'] : [];
                $total = isset($params['total']) ? $params['total'] : [];

                if(count($prolist) <= 0)
                {
                    $this->error(__('未选择入库商品，请重新选择'));
                    exit;
                }

                if(count($nums) <= 0)
                {
                    $this->error(__('未填写入库商品数量，请重新填写'));
                    exit;
                }

                if(count($price) <= 0)
                {
                    $this->error(__('未填写入库商品单价，请重新填写'));
                    exit;
                }

                if(count($total) <= 0)
                {
                    $this->error(__('未填写入库商品总价，请重新填写'));
                    exit;
                }

                //商品与数量的个数不相等
                if(count($prolist) != count($nums))
                {
                    $this->error(__('入库商品的个数与数量不相等，请重新填写'));
                    exit;
                }

                //商品与价格的个数不相等
                if(count($prolist) != count($price))
                {
                    $this->error(__('入库商品的个数与商品价格个数不相等，请重新填写'));
                    exit;
                }

                if(count($prolist) != count($total))
                {
                    $this->error(__('入库商品的个数与商品总价个数不相等，请重新填写'));
                    exit;
                }

                //查找供应商
                $supplierid = isset($params['supplierid']) ? trim($params['supplierid']) : 0;
                $suppliername = model('Depot.Supplier')->where(['id' => $supplierid])->value('name');

                $params['code'] = build_code("ST");
                $params['status'] = 0;
                $params['adminid'] = $this->auth->id;

                //插入入库记录
                $StorageStatus = $ModelStorage->validate("Common/Depot/Storage/Storage")->save($params);

                if($StorageStatus === FALSE)
                {
                    $this->error($ModelStorage->getError());
                    exit;
                }

                //插入入库商品
                $StorageProduct = [];
                foreach($prolist as $key=>$item)
                {
                    $StorageProduct[] = [
                        "storageid"=>$ModelStorage->id,
                        "proid"=>$item,
                        "nums"=>$nums[$key] > 0 ? $nums[$key] : 1,
                        "price"=>$price[$key] >= 0 ? $price[$key] : 0,
                        "total"=>$total[$key] >= 0 ? $total[$key] : 0,
                    ];
                }

                //插入入库商品关系表
                $StorageProductStatus = $ModelStorageProduct->validate("Common/Depot/Storage/Product")->insertAll($StorageProduct);

                if($StorageProductStatus === FALSE)
                {
                    $ModelStorage->rollBack();
                    $this->error($ModelStorageProduct->getError());
                    exit;
                }

                //提交事务
                if($StorageStatus === FALSE || $StorageProductStatus === FALSE)
                {
                    $ModelStorage->rollBack();
                    $ModelStorageProduct->rollBack();
                    $this->error(__('添加入库失败'));
                    exit;
                }else
                {
                    $ModelStorage->commit();
                    $ModelStorageProduct->commit();
                    $this->success();
                    exit;
                }
            }
        }

        $this->view->assign('typelist', build_select('type', model('Depot.Storage.Storage')->typelist(),[], ['class' => 'form-control selectpicker']));

      return $this->view->fetch();
    }

    // 编辑入库
    public function edit($ids = null)
    {
        $row = $this->model->with(['supplier'])->find($ids);

        if(!$row)
        {
            $this->error('无入库数据');
            exit;
        }

        //查询入库商品
        $product = $this->DepotProductModel->with(['products'])->where(['storageid'=>$ids])->select();

        //提取所有的入库商品id
        $proids = array_column($product, 'proid');

        if($this->request->isPost())
        {
            $params = $this->request->post();
            
            if($params)
            {
                $ModelProduct = model('Product.Product');

                //入库插入
                $ModelStorage = model('Depot.Storage.Storage');
                $ModelStorageProduct = model('Depot.Storage.Product');
                $ModelStorage->startTrans();
                $ModelStorageProduct->startTrans();

                //循环入库商品
                $prolist = isset($params['prolist']) ? $params['prolist'] : [];
                $nums = isset($params['nums']) ? $params['nums'] : [];
                $price = isset($params['price']) ? $params['price'] : [];
                $total = isset($params['total']) ? $params['total'] : [];

                if(count($prolist) <= 0)
                {
                    $this->error(__('未选择入库商品，请重新选择'));
                    exit;
                }

                if(count($nums) <= 0)
                {
                    $this->error(__('未填写入库商品数量，请重新填写'));
                    exit;
                }

                if(count($price) <= 0)
                {
                    $this->error(__('未填写入库商品单价，请重新填写'));
                    exit;
                }

                if(count($total) <= 0)
                {
                    $this->error(__('未填写入库商品总价，请重新填写'));
                    exit;
                }

                //商品与数量的个数不相等
                if(count($prolist) != count($nums))
                {
                    $this->error(__('入库商品的个数与数量不相等，请重新填写'));
                    exit;
                }

                //商品与价格的个数不相等
                if(count($prolist) != count($price))
                {
                    $this->error(__('入库商品的个数与商品价格个数不相等，请重新填写'));
                    exit;
                }

                if(count($prolist) != count($total))
                {
                    $this->error(__('入库商品的个数与商品总价个数不相等，请重新填写'));
                    exit;
                }

                //查找供应商
                $supplierid = isset($params['supplierid']) ? trim($params['supplierid']) : 0;
                $suppliername = model('Depot.Supplier')->where(['id' => $supplierid])->value('name');

                $params['code'] = $row['code'];
                $params['adminid'] = $row['adminid'];
                $params['id'] = $row['id'];
                $params['status'] = $row['status'];

                //更新入库记录
                $StorageStatus = $ModelStorage->validate("Common/Depot/Storage/Storage")->isUpdate(true)->save($params);

                if($StorageStatus === FALSE)
                {
                    $this->error($ModelStorage->getError());
                    exit;
                }

                //入库商品
                $StorageProductAdd = [];
                $StorageProductUpdate = [];
                foreach($prolist as $key=>$item)
                {
                    $exist = $ModelStorageProduct->where(['storageid'=>$row['id'], 'proid'=>$item])->find();

                    //存在就更新
                    if($exist)
                    {
                        //删除提取的ids
                        $pos = array_search($item, $proids);
                        $pos = ($pos === FALSE) ? -1 : $pos;
                        unset($proids[$pos]);

                        $StorageProductUpdate[] = [
                            "id"=>$exist['id'],
                            "storageid"=>$row['id'],
                            "proid"=>$item,
                            "nums"=>$nums[$key] > 0 ? $nums[$key] : 1,
                            "price"=>$price[$key] >= 0 ? $price[$key] : 0,
                            "total"=>$total[$key] >= 0 ? $total[$key] : 0,
                        ];
                    }else
                    {
                        //不存在就插入
                        $StorageProductAdd[] = [
                            "storageid"=>$row['id'],
                            "proid"=>$item,
                            "nums"=>$nums[$key] > 0 ? $nums[$key] : 1,
                            "price"=>$price[$key] >= 0 ? $price[$key] : 0,
                            "total"=>$total[$key] >= 0 ? $total[$key] : 0,
                        ];
                    } 
                }

                //插入入库商品关系表
                if(!empty($StorageProductAdd))
                {
                    $StorageProductAddStatus = $ModelStorageProduct->validate("Common/Depot/Storage/Product")->insertAll($StorageProductAdd);

                    if($StorageProductAddStatus === FALSE)
                    {
                        $ModelStorage->rollBack();
                        $this->error($ModelStorageProduct->getError());
                        exit;
                    }
                }

                // 更新入库商品关系表
                if(!empty($StorageProductUpdate))
                {
                    $StorageProductUpdateStatus = $ModelStorageProduct->validate("Common/Depot/Storage/Product")->isUpdate(true)->saveAll($StorageProductUpdate);

                    if($StorageProductUpdateStatus === FALSE)
                    {
                        $ModelStorageProduct->rollBack();
                        $ModelStorage->rollBack();
                        $this->error($ModelStorageProduct->getError());
                        exit;
                    }
                }

                //删除入库商品关系表
                if(!empty($proids))
                {
                    $where = [
                        'storageid' => $row['id'],
                        'proid' => ['in',$proids],
                    ];

                    $StorageProductDeleteStatus = $ModelStorageProduct->where($where)->delete();

                    if($StorageProductDeleteStatus === FALSE)
                    {
                        $ModelStorageProduct->rollBack();
                        $ModelStorage->rollBack();
                        $this->error($ModelStorageProduct->getError());
                        exit;
                    }
                }

                //提交事务
                if($StorageStatus === FALSE)
                {
                    $ModelStorageProduct->rollBack();
                    $ModelStorage->rollBack();
                    $this->error(__('编辑入库失败'));
                    exit;
                }else
                {
                    $ModelStorage->commit();
                    $ModelStorageProduct->commit();
                    $this->success();
                    exit;
                }
            }
        }

        $this->view->assign('row', $row);
        $this->view->assign('product', $product);

        $this->view->assign('typelist', build_select('type', model('Depot.Storage.Storage')->typelist(), $row['type'], ['class' => 'form-control selectpicker']));
        
        return $this->view->fetch();
    }

    // 软删除
    public function del($ids = null)
    {
        $row = $this->model->select($ids);

        if(!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids);

        if ($result === FALSE)
        {
            $this->error($this->model->getError());
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 回收站
    public function recyclebin()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->with(['supplier'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }

    // 还原
    public function restore($ids = NULL)
    {
        //根据id判断数据是否存在
        $rows = $this->model->withTrashed()->whereIn('id', $ids)->select();
        
        if(!$rows)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->restore(['id'=>['in', $ids]]);

        if($result === FALSE)
        {
            $this->error('恢复数据失败');
            exit;
        }else
        {
            $this->success('恢复数据成功');
            exit;
        }
    }

    // 真实删除
    public function destroy($ids = null)
    {
        $row = $this->model->onlyTrashed()->select($ids);

        if (!$row)
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids, true);

        if($result === false)
        {
            $this->error($this->model->getError());
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 入库详情
    public function info($ids = null)
    {
        $row = $this->model->withTrashed()->with(['admin','reviewer'])->find($ids);

        $supplier = $this->SupplierModel->with(['provinces','citys','districts'])->where('id',$row['supplierid'])->find();

        $list = $this->DepotProductModel->where(['storageid' => $row['id']])->select();

        $prolist = [];

        foreach($list as $item)
        {
            $product = model('Product.Product')->with(['type','unit'])->find($item['proid']);

            $prolist[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];
        }

        $this->view->assign([
            'row' => $row,
            'supplier' => $supplier,
            'prolist' => $prolist
        ]);

        return $this->view->fetch();
    }

    // 入库审核
    public function agree($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $data = [
            'status' => '2',
            'reviewerid' => $this->auth->id
        ];

        $result = $this->model->where(['id' => ['in', $ids]])->update($data);
        
        if($result === FALSE)
        {
            $this->error('审核失败');
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 拒绝审核
    public function reject($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $data = [
            'status' => '1',
            'reviewerid' => $this->auth->id
        ];

        $result = $this->model->where(['id' => ['in', $ids]])->update($data);
        
        if($result === FALSE)
        {
            $this->error('审核失败');
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }
    
    // 撤回审核
    public function revoke($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $data = [
            'status' => '0',
            'reviewerid' => NULL
        ];

        $result = $this->model->where(['id' => ['in', $ids]])->update($data);
        
        if($result === FALSE)
        {
            $this->error('撤回失败');
            exit;
        }else
        {
            $this->success();
            exit;
        }
    }

    // 确认入库
    public function confirm($ids = NULL)
    {
        $row = $this->model->find($ids);

        if (!$row) 
        {
            $this->error(__('No Results were found'));
            exit;
        }

        $ProductList = $this->DepotProductModel->where(['storageid' => ['IN', $ids]])->select();
        
        // 开启事务
        $this->model->startTrans();
        $this->ProductModel->startTrans();

        // 更新入库表的数据
        $data = [
            'id' => $ids,
            'status' => 3,
        ];

        $StorageStatus = $this->model->isUpdate(true)->save($data);

        if($StorageStatus === FALSE)
        {
            $this->error($this->model->getError());
            exit;
        }

        // 封装更新库存
        $ProductData = [];

        // 遍历商品
        foreach($ProductList as $item)
        {
            $product = $this->ProductModel->find($item['proid']);
            
            if(!$product)
            {
                continue;
            }

            $ProductData[] = [
                'id' => $product['id'],
                'stock' => bcadd($product['stock'], $item['nums'])
            ];
        }

        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

        if($ProductStatus === FALSE)
        {
            $this->model->rollback();
            $this->error($this->ProductModel->getError());
            exit;
        }
        
        if($StorageStatus === FALSE || $ProductStatus === FALSE)
        {
            $this->ProductModel->rollback();
            $this->model->rollback();
            $this->error('确认入库失败');
            exit;
        }else
        {
            $this->model->commit();
            $this->ProductModel->commit();
            $this->success('确认入库成功');
            exit;
        }
    }
}
